package com.zhibo.controller.base;
import org.solar.util.StringUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import java.beans.PropertyEditorSupport;
import java.text.SimpleDateFormat;
import java.util.Date;

@Controller
public class BaseController {
    @InitBinder
    public void initBinder(WebDataBinder binder) {
        /**
         * 使用WebDataBinder注册一个自定义的编辑器，编辑器是日期类型
         * 使用属性编辑器实现：重载setAsText,getAsText
         */
        binder.registerCustomEditor(Date.class, new PropertyEditorSupport() {

            @Override
            public String getAsText() {
                return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
                        .format((Date) getValue());
            }

            @Override
            public void setAsText(String text) {
                if (text==null||"".equals(text)){
                    setValue(null);
                    return;
                }
                SimpleDateFormat sdf=null;
                if (text.length()>16){
                    sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                }else if (StringUtil.isNumeric(text)){
                       Long time=Long.valueOf(text);
                       setValue(new Date(time));
                       return;
                }else {

                    sdf=new SimpleDateFormat("yyyy-MM-dd");

                }
                try {
                    setValue(sdf.parse(text));
                } catch (Exception e) {
                    e.printStackTrace();
                    setValue(null);
                }
            }

        });
    }



}
